package map.core;

import map.core.util.MapHelper;
import org.geotools.coverage.CoverageFactoryFinder;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.geometry.GeneralBounds;
import org.geotools.util.factory.Hints;

import java.awt.image.*;
import java.io.IOException;
import java.util.Arrays;


/**
 * 最上方是第1行，是左则是第1列，左上角（0，0)
 */
public class MemoryRasterLayer extends RasterLayer{
    private int width;
    private int height;

    private LonLatBounds bounds;

    float[] data;

    public MemoryRasterLayer(int width, int height,LonLatBounds bounds,float defaultValue) {
        this.width = width;
        this.height = height;
        this.data = new float[width*height];
        Arrays.fill(data,defaultValue);

        this.bounds = bounds;
    }

    /**
     *
     * @param column 列号，从0开始
     * @param row 行号，从0开始
     * @param value
     */
    public void setPixel(int column,int row,float value){
        int index = row*width + column;
        data[index] = value;
    }

    public float getPixel(int column,int row){
        int index = row*width + column;
       return data[index] ;
    }

    private   GridCoverage2D createGridCoverage2D() throws IOException {
        System.out.println("走了");
        int bands = 1;
        int[] bandOffsets = {0};

        SampleModel sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_FLOAT, width, height, bands, width  * bands, bandOffsets);
        DataBuffer buffer = new DataBufferFloat(width * height * bands);
        WritableRaster raster = Raster.createWritableRaster(sampleModel, buffer, null);

         for(int i = 0 ;i < width ; i ++){
            for(int j = 0 ; j < height ; j ++){
                float value = getPixel(i,j);
                raster.setSample(i,j,0,value);
            }
        }

        final Hints hints = new Hints();
        final GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(hints);

        final GeneralBounds envelope = new GeneralBounds(MapHelper.CRS_4326);
        envelope.setRange(0, bounds.getMinLon(), bounds.getMaxLon());
        envelope.setRange(1,bounds.getMinLat(),bounds.getMaxLat());

        return factory.create("cov",raster,envelope);
    }


    public   GridCoverage2D getGridData(int slice){
        if(slice != 0){
            throw new RuntimeException("slice必须等于0");
        }
        try {
            return createGridCoverage2D();
        } catch (IOException e) {
            throw  new RuntimeException(e);
        }
    }


    @Override
    public LonLatBounds getBounds() {
        return bounds;
    }

    @Override
    public int getWidth() {
        return width;
    }

    @Override
    public int getHeight() {
       return height;
    }
}
